from django.shortcuts import render, redirect
from django.views import View
from user_manage import models


# Create your views here.
def login_required(func):
    def inner(obj, request, *args, **kwargs):
        login = request.session.get('login')
        if login != '1':
            url = request.path_info
            return redirect('/login/?from=%s' % url)
        return func(obj, request, *args, **kwargs)

    return inner


class Index(View):
    @login_required
    def get(self, request):
        return render(request, 'index.html')

    def post(self, request):
        pass


class Home(View):
    @login_required
    def get(self, request):
        return render(request, 'home.html')

    def post(self, request):
        pass


class Login(View):
    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        error = ''
        username = request.POST.get('username')
        password = request.POST.get('password')
        users = models.Userinfo.objects.filter(username=username)
        if users:
            for user in users:
                if password == user.password:
                    url = request.GET.get('from')
                    if url:
                        ret = redirect(url)
                    else:
                        ret = redirect('/index/')
                    request.session['login'] = '1'
                    return ret
                else:
                    error = '密码错误'
        else:
            error = '用户名不存在'
        return render(request, 'login.html', {'error': error})


class Adduser(View):
    def get(self, request):
        return render(request, 'add_user.html')

    def post(self, request):
        user = request.POST.get('username')
        pwd = request.POST.get('password')
        age = request.POST.get('age')
        gender = request.POST.get('gender')
        ret = models.Userinfo.objects.filter(username=user)
        print(ret)
        if not ret:
            models.Userinfo.objects.create(username=user, password=pwd, age=age, gender=gender)
            return redirect('/login/')
        return render(request, 'add_user.html', {'error': '用户已存在'})
